<?php
namespace app\common\service;

class Upload
{
    /**
     * 上传图片
     * @param file $file 图片文件
     * @param string $dir 保存目录
     * @return array
     */
    public function image($file, $dir = 'images')
    {
        $info = $file->validate(['size'=>2097152,'ext'=>'jpg,jpeg,png,gif'])
            ->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $dir);
            
        if ($info) {
            $url = '/uploads/' . $dir . '/' . str_replace('\\', '/', $info->getSaveName());
            return ['code' => 1, 'msg' => '上传成功', 'data' => ['url' => $url]];
        }
        
        return ['code' => 0, 'msg' => $file->getError()];
    }

    /**
     * 上传视频
     * @param file $file 视频文件
     * @param string $dir 保存目录
     * @return array
     */
    public function video($file, $dir = 'videos')
    {
        $info = $file->validate(['size'=>52428800,'ext'=>'mp4,avi,mov'])
            ->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $dir);
            
        if ($info) {
            $url = '/uploads/' . $dir . '/' . str_replace('\\', '/', $info->getSaveName());
            return ['code' => 1, 'msg' => '上传成功', 'data' => ['url' => $url]];
        }
        
        return ['code' => 0, 'msg' => $file->getError()];
    }
}